package com.dao;
/**
 * @author      Bo Li, Hailun Zhang, Ni Xin, Xiang Xiao
 * @version     1.6                              
 * @since       2012-08-05         
 */
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


import com.tools.GenerateRandom;

import com.jndiLocator.getSourceLocator;

import com.bean.UserBean;

public class UserDao {
	
	/**
	 * Login function.
	 *
	 * @param userId       the id of the user
	 * @param password	   the password of the user
	 * @throws     		   Exception
	 */
	public UserBean login(String userId,String password)throws Exception{
		String token = "";
		UserBean  userBean = new UserBean();
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try{
			conn = getSourceLocator.ds.getConnection();
			String sql ="select * " +
					" from person " +
					"where person_id =? and password =?";
			pstmt =conn.prepareStatement(sql);
			pstmt.setString(1, userId);
			pstmt.setString(2, password);
			rs = pstmt.executeQuery();
			if(rs.next()){
				userBean.setAccountId(rs.getString("person_id"));
				userBean.setUserName(rs.getString("name"));
				userBean.setRole(rs.getString("role"));
				token = new GenerateRandom().GenerateRandomString();
				this.addSession(userId, token);
				userBean.setToken(token);
			}
			else
				throw new Exception("Invalid");
		}
		catch(SQLException e){
			e.printStackTrace();
		}
		finally{
			if (conn != null && pstmt != null) {
				conn.close();
				pstmt.close();
			}
		}		
		return userBean;
	}
	
	/**
	 * Checks the token given by the user has been recorded in the list.
	 *
	 * @param userId       the id of the user
	 * @param token	       the token generated by the user
	 * @return    		   success or failure
	 * @throws     		   Exception
	 */
	public Boolean getAuth(String userId,String token)throws Exception{
		Boolean success = false;
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try{
			conn = getSourceLocator.ds.getConnection();
			String sql ="select count(1) from session where user_id = ? and user_token = ? and login_time >timestampadd(minute, -30, current_timestamp)";
			pstmt =conn.prepareStatement(sql);
			pstmt.setString(1, userId);
			pstmt.setString(2, token);
			rs = pstmt.executeQuery();
			if(rs.next()&&rs.getInt(1)==1){
				success = true;
			}
			else
				throw new Exception("invalid");
		}
		catch(SQLException e){
			e.printStackTrace();
		}
		finally{
			if (conn != null && pstmt != null) {
				conn.close();
				pstmt.close();
			}
		}
		return success;
	}
	
	/**
	 * Checks the operation of adding a session is successful.
	 *
	 * @param userId       the id of the user
	 * @param token	       the token generated by the user
	 * @return    		   success or failure
	 * @throws     		   Exception
	 */
	private Boolean addSession(String userId,String token) throws Exception{
		Connection conn = null;
		Boolean success = false;
		PreparedStatement pstmt = null;
		try{
			conn = getSourceLocator.ds.getConnection();
			String sql ="update session set user_token = ?, login_time = current_timestamp where user_id = ? ";
			pstmt =conn.prepareStatement(sql);
			pstmt.setString(1, token);
			pstmt.setString(2, userId);
			pstmt.executeUpdate();
		    success =true;
		    conn.commit();
		}
		catch(Exception e){
			conn.rollback();
			throw new Exception("internal error!");
		}
		finally{
			if (conn != null && pstmt != null) {
				conn.close();
				pstmt.close();
			}
		}
		return success;
	}
	
	/**
	 * Gets the role according to the user id.
	 *
	 * @param userId       the id of the user
	 * @return    		   the role
	 * @throws     		   Exception
	 */
	public String getUserRole(String userId) throws Exception{
		String role = "";
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try{
			conn = getSourceLocator.ds.getConnection();
			String sql ="select role " +
					" from person " +
					"where person_id =?";
			pstmt =conn.prepareStatement(sql);
			pstmt.setString(1, userId);
			rs = pstmt.executeQuery();
			if(rs.next()){
				role = rs.getString("role");
			}
			else
				throw new Exception("Invalid");
		}
		catch(SQLException e){
			e.printStackTrace();
			throw e;
		}
		finally{
			if (conn != null && pstmt != null) {
				conn.close();
				pstmt.close();
			}
		}		
		return role;
	}
	
	/**
	 * Registers a new user.
	 *
	 * @param userId       the id of the user
	 * @param password	   the password of the user
	 * @param role		   the role of the user
	 * @throws     		   Exception
	 */
	public void registerUser(String userId,String userName,String password, String role) throws Exception{;
		Connection conn = null;
		PreparedStatement pstmt = null;
		try{
			conn = getSourceLocator.ds.getConnection();
			String sql ="insert into person (person_id,name,password,role) value(?,?,?,?)";
			pstmt =conn.prepareStatement(sql);
			pstmt.setString(1, userId);
			pstmt.setString(2, userName);
			pstmt.setString(3, password);
			pstmt.setString(4, role);
			pstmt.executeUpdate();
			conn.commit();
			String sessionSql ="insert into session (user_id) value(?)";
			pstmt =conn.prepareStatement(sessionSql);
			pstmt.setString(1, userId);
			pstmt.executeUpdate();
			conn.commit();
		}
		catch(SQLException e){
			throw e;
		}
		finally{
			if (conn != null && pstmt != null) {
				conn.close();
				pstmt.close();
			}
		}
	}
	
	/**
	 * Checks whether the user exists (already recorded).
	 *
	 * @param userId       the id of the user
	 * @return			   success or failure
	 * @throws     		   Exception
	 */
	public boolean checkExistingAccount(String userId)throws Exception{
		Boolean exist = null;
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try{
			conn = getSourceLocator.ds.getConnection();
			String sql ="select person_id from person where person_id = ?";
			pstmt =conn.prepareStatement(sql);
			pstmt.setString(1, userId);
			rs = pstmt.executeQuery();
			if(rs.next()){
				exist = true;
			}
			else
				exist = false;
		}
		catch(SQLException e){
			e.printStackTrace();
			throw e;
		}
		finally{
			if (conn != null && pstmt != null) {
				conn.close();
				pstmt.close();
			}
		}		
		return exist;
	}
	
	public List<UserBean> getUnsignedStudentsByProject(String projectId) throws Exception {
		List<UserBean> userBeans = new ArrayList<UserBean>();
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try{
			conn = getSourceLocator.ds.getConnection();
			String sql ="select p.person_id,p.name,p.role from person p," +
					" project pj,enrollcourse ec where ec.course_id = pj.course_id " +
					"and pj.project_id = ? and ec.student_id = p.person_id and p.person_id " +
					" not in(select eg.student_id from enrollgroup eg, `group` g where eg.group_id" +
					" = g.group_id  and g.project_id = ?)";
			pstmt =conn.prepareStatement(sql);
			pstmt.setInt(1, Integer.parseInt(projectId));
			pstmt.setInt(2, Integer.parseInt(projectId));
			rs = pstmt.executeQuery();
			while(rs.next()){
				UserBean  userBean = new UserBean();
				userBean.setAccountId(rs.getString("person_id"));
				userBean.setUserName(rs.getString("name"));
				userBean.setRole(rs.getString("role"));
				userBeans.add(userBean);
			}
		}
		catch(SQLException e){
			e.printStackTrace();
			throw e;
		}
		finally{
			if (conn != null && pstmt != null) {
				conn.close();
				pstmt.close();
			}
		}		
		return userBeans;
	}
	
	public boolean checkLecturerAuth(String userId,String projectId)throws Exception{
		Boolean exist = null;
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try{
			conn = getSourceLocator.ds.getConnection();
			String sql ="SELECT c.course_id FROM course c, project p where c.lecturer_id = ? and p.project_id = ?";
			pstmt =conn.prepareStatement(sql);
			pstmt.setString(1, userId);
			pstmt.setInt(2, Integer.parseInt(projectId));
			rs = pstmt.executeQuery();
			if(rs.next()){
				exist = true;
			}
			else
				exist = false;
		}
		catch(SQLException e){
			e.printStackTrace();
			throw e;
		}
		finally{
			if (conn != null && pstmt != null) {
				conn.close();
				pstmt.close();
			}
		}		
		return exist;
	}
}
